package com.yimi.yinhepda.views.load_module

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.CheckBox
import android.widget.TextView
import com.pda.uce.commom.util.LoadUtils
import com.pda.uce.commom.util.LogUtil
import com.pda.uce.commom.util.MyDialog
import com.pda.ym.callbacks.UICallBack
import com.pda.ym.db.table.UnloadScanTable
import com.pda.ym.entity.bean.CarPlanTaskEntity
import com.pda.ym.entity.bean.LoadBillTaskEntity
import com.pda.ym.entity.response.NoDataResponse
import com.pda.ym.net.NetRequest
import com.pda.ym.utils.Constants
import com.pda.ym.utils.DateHelper
import com.pda.ym.utils.SharedPreferUtil
import com.pda.ym.utils.SoundVibratorManager
import com.yimi.yinhepda.callbacks.OnClickCallBack
import com.yimi.yinhepda.db.dao.DepartmentTableDao
import com.yimi.yinhepda.db.dao.UnloadScanTableDao
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao
import com.yimi.yinhepda.db.table.UnloadTaskTable
import com.yimi.yinhepda.entity.bean.CheckBoxItemEntity
import com.yimi.yinhepda.entity.bean.JoinPeopleEntity
import com.yimi.yinhepda.entity.bean.LoaderEntity
import com.yimi.yinhepda.entity.request.AddLoaderEmpRequest
import com.yimi.yinhepda.entity.request.CancleScanLoad
import com.yimi.yinhepda.entity.request.CancleScanLoadRequest
import com.yimi.yinhepda.entity.request.QueryLoadTaskV2Request
import com.yimi.yinhepda.entity.response.*
import com.yimi.yinhepda.event.CreateStowagesEvent
import com.yimi.yinhepda.event.ScanResult
import com.yimi.yinhepda.utils.*
import com.yimi.yinhepda.views.unload_module.UnloadScanActivity
import org.greenrobot.eventbus.EventBus
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.Serializable
import java.sql.SQLException
import java.util.*

/**
 * @author: lj
 * Date: 2020/6/11 10:06
 * Description:
 */
object LoadUtil {
    /**
     * 融合：创建装车任务
     *
     * @param mSelectNextDepts     已选择的下一站
     * @param mCarPlaneTasks       装车计划任务
     * @param joinPeopleEntityList 参与人
     * @param createType 0-全部，1-快运，2-快递
     * @param callBack             创建结果回调
     */
    @JvmStatic
    fun createLoadTask(mSelectNextDepts: List<CheckBoxItemEntity>, mCarPlaneTasks: List<CarPlanTaskEntity>,
                       joinPeopleEntityList: List<JoinPeopleEntity>, createType: Int?, callBack: UICallBack) {

        mCarPlaneTasks.forEach { planTask ->
            if (planTask.beTask == 1) {
                planTask.loadTasks?.forEach { loadTask ->
                    loadTask.isCheck = false
                }
                planTask.nodes?.forEach { node ->
                    node.isSelected = false
                }
            }
        }

        val requests: MutableList<QueryLoadTaskV2Request> = ArrayList()
        for (selected in mSelectNextDepts) {
            //选择的下一站是否匹配到已存在的装车任务
            var exitNext = false
            var ymExitNext = false
            var ucExitNext = false
            //选择的下一站匹配到的发车计划中的下一站任务
            var tempTaskEntity: CarPlanTaskEntity? = null
            var tempLoadEntity = LoadBillTaskEntity()

            for (taskEntity in mCarPlaneTasks) {
                if (taskEntity.beTask == 1) {
                    if (taskEntity.loadTasks != null) {
                        for (loadTask in taskEntity.loadTasks) {
                            if (createType == 1) {
                                //快运
                                if (loadTask.stowageNo.startsWith("P")) {
                                    if (selected.code == loadTask.destDeptCode) {
                                        loadTask.isCheck = true
                                        exitNext = true
                                        tempLoadEntity = loadTask
                                    }
                                }
                            } else if (createType == 2) {
                                //快递
                                if (!loadTask.stowageNo.startsWith("P")) {
                                    if (selected.code == loadTask.destDeptCode) {
                                        loadTask.isCheck = true
                                        exitNext = true
                                        tempLoadEntity = loadTask
                                    }
                                }
                            } else {
                                //全部
                                if (loadTask.stowageNo.startsWith("P")) {
                                    if (selected.code == loadTask.destDeptCode) {
                                        loadTask.isCheck = true
                                        ymExitNext = true
                                        tempLoadEntity = loadTask
                                    }
                                } else {
                                    if (selected.code == loadTask.destDeptCode) {
                                        loadTask.isCheck = true
                                        ucExitNext = true
                                        tempLoadEntity = loadTask
                                    }
                                }
                            }
                        }
                    }
                    for (node in taskEntity.nodes) {
                        if (selected.code == node.taskNodeCode && selected.nodeNum == node.nodeNum) {
                            tempTaskEntity = taskEntity
                            node.isSelected = true
                        }
                    }
                }
            }

            if (createType == 0) {
                exitNext = !(!ymExitNext || !ucExitNext)
            }

            //下一站没有匹配到装车任务，建立装车任务请求实体
            if (!exitNext && tempTaskEntity != null) {
                val request = QueryLoadTaskV2Request()
                request.taskNo = tempTaskEntity.taskNo
                request.stowageNo = tempLoadEntity.stowageNo
                request.stowageSource = 6
                request.source = 6
                request.srcDeptCode = SharedPreferUtil.getInstance().deptCode
                request.srcDeptName = SharedPreferUtil.getInstance().getValue(Common.DEPT_NAME)
                request.destDeptCode = selected.code
                request.destDeptName = selected.name
                request.carNo = tempTaskEntity.vehNo
                tempTaskEntity.planStartTime?.let { planSTime ->
                    val planDate = DateHelper.StrToDate(planSTime, DateHelper.timeFormat)
                    request.planStartTime = DateHelper.DateToStr(planDate, DateHelper.timeFormat)
                }
                request.taskType = 1
                request.createType = createType
                val loaderEntityList: MutableList<LoaderEntity> = ArrayList()
                var hasLeader = false
                for (entity in joinPeopleEntityList) {
                    val loaderEntity = LoaderEntity()
                    loaderEntity.empCode = entity.userCode
                    loaderEntity.empName = entity.userName
                    if (SharedPreferUtil.getInstance().getValue(Common.USER_CODE) == entity.userCode) {
                        loaderEntity.isLeader = 1
                        hasLeader = true
                    } else {
                        loaderEntity.isLeader = 2
                    }
                    loaderEntityList.add(loaderEntity)
                }
                if (!hasLeader) {
                    //没有主责任，则默认添加登录人为主责任
                    val loaderLeader = LoaderEntity()
                    loaderLeader.empCode = SharedPreferUtil.getInstance().getValue(Common.USER_CODE)
                    loaderLeader.empName = SharedPreferUtil.getInstance().empName
                    loaderLeader.isLeader = 1
                    loaderEntityList.add(loaderLeader)
                }
                request.addLoaders = loaderEntityList
                requests.add(request)
            }
        }
        if (requests.size <= 0) { //下一站都匹配到装车任务，无需请求接口创建，直接返回
            callBack.onSuccess(false)
        } else {
            requestLoadTask(mCarPlaneTasks, requests, 0, callBack)
        }
    }

    /**
     * 多个下一站循环请求创建配载单/发件任务/到件任务
     */
    private fun requestLoadTask(mCarPlaneTasks: List<CarPlanTaskEntity>, requests: List<QueryLoadTaskV2Request>,
                                index: Int, callBack: UICallBack) {
        if (index < requests.size) {
            val request = requests[index]
            NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setUrl(Constants.URL_V2_CREATE_STOWAGE_TASK)
                    .setRequestObject(request)
                    .setResponsClazz(QueryLoadTaskV2Response::class.java)
                    .execute(object : UICallBack() {
                        override fun onError(msg: String) {
                            callBack.onError(msg)
                        }

                        override fun onSuccess(obj: Any) {
                            val response = obj as QueryLoadTaskV2Response
                            if (response != null && response.data != null && response.data.stowageNos != null) {
                                val stowageList = response.data.stowageNos
                                for (stowageNo in stowageList) {
                                    for (taskEntity in mCarPlaneTasks) {
                                        if (request.taskNo == taskEntity.taskNo) {
                                            //新创建的装车任务是否存在，没有则创建添加进发车计划中
                                            var exitStowageNo = false
                                            if (taskEntity.loadTasks != null) {
                                                for (loadTask in taskEntity.loadTasks) {
                                                    if (stowageNo == loadTask.stowageNo) {
                                                        loadTask.isCheck = true
                                                        exitStowageNo = true
                                                    }
                                                }
                                            } else {
                                                taskEntity.loadTasks = ArrayList()
                                            }
                                            if (!exitStowageNo) { //组装新的装车任务
                                                val loadTask = LoadBillTaskEntity()
                                                loadTask.isCheck = true
                                                loadTask.stowageNo = stowageNo
                                                loadTask.srcDeptCode = request.srcDeptCode
                                                loadTask.srcDeptName = request.srcDeptName
                                                loadTask.destDeptCode = request.destDeptCode
                                                loadTask.destDeptName = request.destDeptName
                                                loadTask.carNo = request.carNo
                                                taskEntity.loadTasks.add(loadTask)
                                            }
                                        }
                                    }
                                }
                            }
                            //继续请求创建装车任务
                            requestLoadTask(mCarPlaneTasks, requests, index + 1, callBack)
                        }
                    })
        } else { //选择的下一站循环创建完成后返回
            callBack.onSuccess(true)
        }
    }

    /**
     * 融合：卸车修改装卸人接口
     *
     * @param joinPeopleEntityList 参与人集合
     * @param mCarPlaneTasks       发车任务计划
     * @param mUnLoadTaskList      已选择的装卸车任务集合
     * @param scanType             扫描类型：10-融合装车，11-融合卸车
     * @param PlatformNum          月台号
     * @param callBack             请求接口回调
     */
    @JvmStatic
    fun addLoaderEmpCodes(joinPeopleEntityList: List<JoinPeopleEntity>?, mCarPlaneTasks: List<CarPlanTaskEntity>,
                          scanType: Int, PlatformNum: String?, callBack: UICallBack) {

        //参与人被修改后，调用接口修改装卸人
        var updateJoinPeople = false
        for (planTask in mCarPlaneTasks) {
            if (planTask.loadTasks != null) {
                for (loadTask in planTask.loadTasks) {
                    if (loadTask.isCheck) {
                        if (scanType == Common.SCAN_TYPE_MERGE_LOAD) {
                            //融合装车
                            if (loadTask.loadEmpCodes != null) {
                                val empCodeArray = loadTask.loadEmpCodes.split(",")
                                if (empCodeArray.size == joinPeopleEntityList?.size) {
                                    //任务装卸人和参与人相等，则比较两者不相等为已修改
                                    for (joinPeople in joinPeopleEntityList) {
                                        if (!loadTask.loadEmpCodes.contains(joinPeople.userCode)) {
                                            updateJoinPeople = true
                                        }
                                    }
                                } else {
                                    //任务装卸人和参与人不相等，则为已修改
                                    updateJoinPeople = true
                                }
                            } else {
                                updateJoinPeople = true
                            }
                        } else {
                            if (loadTask.unloadEmpCodes != null) {
                                val empCodeArray = loadTask.unloadEmpCodes.split(",")
                                if (empCodeArray.size == joinPeopleEntityList?.size) {
                                    //任务装卸人和参与人相等，则比较两者不相等为已修改
                                    for (joinPeople in joinPeopleEntityList) {
                                        if (!loadTask.unloadEmpCodes.contains(joinPeople.userCode)) {
                                            updateJoinPeople = true
                                        }
                                    }
                                } else {
                                    //任务装卸人和参与人不相等，则为已修改
                                    updateJoinPeople = true
                                }
                            } else {
                                updateJoinPeople = true
                            }
                        }
                    }
                }
            }
        }

        if (updateJoinPeople) {
            val request = AddLoaderEmpRequest()
            val stowageNos = mutableListOf<String>()
            for (planTask in mCarPlaneTasks) {
                if (planTask.loadTasks != null) {
                    for (loadTask in planTask.loadTasks) {
                        if (loadTask.isCheck) {
                            stowageNos.add(loadTask.stowageNo)
                        }
                    }
                }
            }
            request.stowageNos = stowageNos
            if (scanType == Common.SCAN_TYPE_MERGE_LOAD) { //融合装车
                request.businessType = 1
            } else { //融合卸车
                request.businessType = 2
            }
            request.platformNo = PlatformNum
            if (joinPeopleEntityList != null) {
                val loaders: MutableList<LoaderEntity> = ArrayList()
                var hasLeader = false
                for (joinPeople in joinPeopleEntityList) {
                    val loaderEntity = LoaderEntity()
                    loaderEntity.empCode = joinPeople.userCode
                    loaderEntity.empName = joinPeople.userName
                    loaderEntity.srcDeptCode = SharedPreferUtil.getInstance().deptCode
                    loaderEntity.compCode = SharedPreferUtil.getInstance().companyCode
                    if (SharedPreferUtil.getInstance().getValue(Common.USER_CODE) == joinPeople.userCode) {
                        loaderEntity.isLeader = 1
                        hasLeader = true
                    } else {
                        loaderEntity.isLeader = 2
                    }
                    loaders.add(loaderEntity)
                }

                if (!hasLeader) {
                    //没有主责任，则默认添加登录人为主责任
                    val loaderLeader = LoaderEntity()
                    loaderLeader.empCode = SharedPreferUtil.getInstance().getValue(Common.USER_CODE)
                    loaderLeader.empName = SharedPreferUtil.getInstance().empName
                    loaderLeader.srcDeptCode = SharedPreferUtil.getInstance().deptCode
                    loaderLeader.compCode = SharedPreferUtil.getInstance().companyCode
                    loaderLeader.isLeader = 1
                    loaders.add(loaderLeader)
                }

                request.addLoaders = loaders
            }
            NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setResponsClazz(DataStrResponse::class.java)
                    .setUrl(Constants.URL_V2_ADD_LOADER_EMPCODES)
                    .setRequestObject(request)
                    .setConnTimeOut(5 * 1000.toLong())
                    .execute(callBack)
        } else {
            callBack.onSuccess(null)
        }
    }

    /**
     * 用于网点卸车修改装车人
     */
    @JvmStatic
    fun addLoaderEmpCodes(carPlaneTasks: List<CarPlanTaskEntity>, callBack: UICallBack) {
        val joinPeoples: MutableList<JoinPeopleEntity> = ArrayList()
        val joinPeople = JoinPeopleEntity()
        joinPeople.userCode = SharedPreferUtil.getInstance().getValue(Common.USER_CODE)
        joinPeople.userName = SharedPreferUtil.getInstance().empName
        joinPeoples.add(joinPeople)
        carPlaneTasks.forEach { planTask ->
            planTask.loadTasks?.forEach { loadTask ->
                loadTask.isCheck = true
            }
        }
        addLoaderEmpCodes(joinPeoples, carPlaneTasks, Common.SCAN_TYPE_MERGE_UNLOAD, "", callBack)
    }

    /**
     * 装车跳转至下一个界面
     *
     * @param context   Context
     * @param taskNo    本地暂存任务号
     * @param planTasks 发车计划任务集合
     */
    @JvmStatic
    fun toNextActivity(context: Context, taskNo: String?, planTasks: List<CarPlanTaskEntity?>?, operType: Int) {
        val deptType = SharedPreferUtil.getInstance().getIntValue(Common.DEPT_TYPE)
        if (deptType == 5 || deptType == 6) {
            //判断是否是分拨,跳转至装卸组
            toClassActivity(context, taskNo, planTasks, LoadUnloadGroupActivity::class.java, operType)
        } else {
            //跳转至装车扫描界面
            toClassActivity(context, taskNo, planTasks, LoadScanActivity::class.java, operType)
        }
    }

    /**
     * 跳转至下一个界面
     *
     * @param context   上下文
     * @param taskNo    本地暂存任务号
     * @param planTasks 发车计划任务集合
     * @param cls       需要跳转的类
     * @param operType 操作类型：1-装车。2-卸车
     */
    @JvmStatic
    fun toClassActivity(context: Context, taskNo: String?, planTasks: List<CarPlanTaskEntity?>?, cls: Class<*>?, operType: Int) {
        val intent = Intent(context, cls)
        val bundle = Bundle()
        //扫描类型：扫描类型：1-装车扫描，2=卸车扫描 ,3-离线装车，4-离线卸车,5-移库装车，6-移库卸车,
        // 7-单独移库卸车，8-分拨自提,9-跨越点货,10-融合装车，11-融合卸车
        if (operType == 1) {
            bundle.putInt("scanType", Common.SCAN_TYPE_MERGE_LOAD)
        } else {
            bundle.putInt("scanType", Common.SCAN_TYPE_MERGE_UNLOAD)
        }
        bundle.putSerializable("carPlaneTasks", planTasks as Serializable?)
        bundle.putString("task", taskNo)
        intent.putExtras(bundle)
        context.startActivity(intent)
    }

    /**
     * 截取班次
     *
     * @param shift 班次
     * @return string
     */
    @JvmStatic
    fun getShift(shift: String?): String? {
        return if (shift != null) {
            if (shift.length > 2) {
                shift.substring(10).toInt().toString()
            } else {
                shift
            }
        } else null
    }

    @JvmStatic
    fun updateStatusForLoad(stowageNo: String?) {
        val mUnloadTaskTableDao = UnloadTaskTableDao()
        //更新数据库状态
        val list = mUnloadTaskTableDao.findDataByStowageNo(stowageNo, 1)
        if (list != null) {
            for (item in list) {
                item.isUpload = 1
                item.status = 1
                try {
                    mUnloadTaskTableDao.update(item)
                } catch (e: SQLException) {
                    LogUtil.e(e.toString())
                }
            }
        }
    }

    /**
     * 根据任务号更新本地暂存任务状态
     */
    @JvmStatic
    fun updateLoadStatus(task: String?) {
        val mUnloadTaskTableDao = UnloadTaskTableDao()
        //更新数据库状态
        val list = mUnloadTaskTableDao.findData(task)
        if (list != null) {
            for (item in list) {
                item.isUpload = 1
                item.status = 1
                try {
                    mUnloadTaskTableDao.update(item)
                } catch (e: SQLException) {
                    LogUtil.e(e.toString())
                }
            }
        }
    }

    /**
     * 获取发车计划下一站
     */
    @JvmStatic
    fun getCarPlanTaskNextDept(planTasks: MutableList<CarPlanTaskEntity>): MutableList<CheckBoxItemEntity> {
        val departTableDao = DepartmentTableDao()
        val mNextDeptList = mutableListOf<CheckBoxItemEntity>()
        planTasks.forEach { planTask ->
            planTask.nodes?.forEach { node ->
                val entity = CheckBoxItemEntity()
                planTask.loadTasks?.forEach { loadTask ->
                    if (node.taskNodeCode == loadTask.destDeptCode) {
                        entity.isCheck = true
                        entity.isTempCheck = true
                    }
                }
                if (!TextUtils.isEmpty(node.taskNodeName)) {
                    entity.name = node.taskNodeName
                } else {
                    val departTable = departTableDao.queryDeptByDeptCode(node.taskNodeCode)
                    if (departTable != null) {
                        entity.name = departTable.deptName
                    } else {
                        entity.name = node.taskNodeCode
                    }
                }
                entity.code = node.taskNodeCode
                entity.nodeNum = node.nodeNum
                entity.beTask = planTask.beTask
                mNextDeptList.add(entity)
            }
        }

        return mNextDeptList
    }

    /**
     * 显示下一站对话框
     * @param context 上下文
     * @param planTasks 发车计划任务
     * @param operType 操作类型：1-装车。2-卸车
     */
    @JvmStatic
    fun showNextDeptDialog(context: Context, planTasks: MutableList<CarPlanTaskEntity>, operType: Int) {

        if (planTasks.size == 1) {
            //只有一个计划发车任务时，选择下一站执行装车任务
            var hasBeTask = false
            planTasks.forEach { planTask ->
                if (planTask.beTask == 1) {
                    hasBeTask = true
                }
            }

            if (!hasBeTask) {
                //非车线任务设置装车任务选中状态
                planTasks.forEach { planTask ->
                    planTask.loadTasks?.forEach { loadTask ->
                        loadTask.isCheck = true
                    }
                }

                saveTaskAndToNextActivity(context, planTasks, operType)
            } else {

                val mNextDeptList = getCarPlanTaskNextDept(planTasks)
                if (mNextDeptList.isNullOrEmpty()) {
                    ToastUtil.showToast("未查询到下一站！")
                    return
                }

                DialogUtil.checkBoxDialog(context, "选择下一站", "创建", "取消", mNextDeptList, true, planTasks, object : OnClickCallBack() {
                    override fun onCancle() {}
                    override fun onSure(obj: Any, obj1: Any) {
                        val mSelectedNextDeptList = obj as MutableList<CheckBoxItemEntity>
                        readyCreateLoadTask(context, planTasks, mSelectedNextDeptList, operType)
                    }
                })
            }
        } else {
            //多个计划发车任务时，选择配载任务执行装车任务
            val loadTaskList = mutableListOf<LoadBillTaskEntity>()
            planTasks.forEach { planTask ->
                planTask.loadTasks?.forEach { loadTask ->
                    loadTask.isCheck = true
                    loadTaskList.add(loadTask)
                }
            }
            //弹框展示装车任务选择框
            DialogUtil.selectTaskDialog(context, loadTaskList, planTasks, object : OnClickCallBack() {
                override fun onCancle() {}

                override fun onSure(obj: Any?, obj1: Any?) {
                    saveTaskAndToNextActivity(context, planTasks, operType)
                }

            })
        }
    }

    private fun readyCreateLoadTask(context: Context, planTasks: MutableList<CarPlanTaskEntity>, selectedNextDeptList: MutableList<CheckBoxItemEntity>, operType: Int) {
        if (!selectedNextDeptList.isNullOrEmpty()) {

            val scanSwitch = SharedPreferUtil.getInstance().getBooleanValue(Constants.MERGE_LOAD_SCAN_TASK_SWITCH)
            if (scanSwitch) {
                //融合装车扫描创建任务开启
                //设置已选中的装车任务状态
                selectedNextDeptList.forEach { selectedNextDept ->
                    planTasks.forEach { planTask ->
                        planTask.loadTasks?.forEach { loadTask ->
                            if (selectedNextDept.code == loadTask.destDeptCode) {
                                loadTask.isCheck = true
                            }
                        }
                        planTask.nodes?.forEach { node ->
                            if (selectedNextDept.code == node.taskNodeCode) {
                                node.isSelected = true
                            }
                        }
                    }
                }

                saveTaskAndToNextActivity(context, planTasks, operType)
            } else {
                //组装装卸人
                val joinPeoples = mutableListOf<JoinPeopleEntity>()
                val joinPeople = JoinPeopleEntity()
                joinPeople.userCode = SharedPreferUtil.getInstance().getValue(Common.USER_CODE)
                joinPeople.userName = SharedPreferUtil.getInstance().empName
                joinPeoples.add(joinPeople)

                var createType = 0
                if (!selectedNextDeptList.isNullOrEmpty()) {
                    createType = selectedNextDeptList[0].createType
                }

                //车线任务，创建装车任务
                LoadUtils.showLoading("创建中...", context)
                createLoadTask(selectedNextDeptList, planTasks, joinPeoples, createType, object : UICallBack() {
                    override fun onSuccess(obj: Any?) {
                        LoadUtils.hideLoading(context)

                        saveTaskAndToNextActivity(context, planTasks, operType)
                    }

                    override fun onError(msg: String?) {
                        LoadUtils.hideLoading(context)
                        ToastUtil.showToast(msg)
                    }
                })
            }
        } else {
            ToastUtil.showToast("选择的下一站集合为空！")
        }
    }

    private fun saveTaskAndToNextActivity(context: Context, planTasks: MutableList<CarPlanTaskEntity>, operType: Int) {
        val task = Constants.getUUID()
        val result = UnloadTaskTableDao().noExitInsert(UnloadTaskTable.parseUnloadTable2(task, planTasks, operType), operType)
        if (result >= 0) {
            toNextScanActivity(context, task, planTasks, operType)
        } else {
            ToastUtil.showToast("保存装车任务失败！")
        }
    }

    /**
     * @param operType 操作类型：1-装车。2-卸车
     */
    private fun toNextScanActivity(context: Context, taskNo: String, planTasks: MutableList<CarPlanTaskEntity>, operType: Int) {
        //跳转至装车扫描界面
        if (operType == 1) {
            toClassActivity(context, taskNo, planTasks, LoadScanActivity::class.java, operType)
        } else {
            toClassActivity(context, taskNo, planTasks, UnloadScanActivity::class.java, operType)
        }
    }

    /**
     * 装卸车运单撤销提示框
     * @param operType 11-装车撤销，22-卸车撤销
     */
    @JvmStatic
    fun showDeleteWaybillDialog(context: Context, result: String, loadInfo: LoadInfo, operType: Int,
                                planTaskList: MutableList<CarPlanTaskEntity>, loadType: Int, callBack: UICallBack) {
        showDeleteWaybillDialog(context, result, loadInfo, null, operType, planTaskList, loadType, callBack)
    }

    @JvmStatic
    fun showDeleteWaybillDialog(context: Context, result: String, loadInfo: LoadInfo?,
                                unloadEntity: QueryUnLoadDetailBillcode?, operType: Int,
                                planTaskList: MutableList<CarPlanTaskEntity>, loadType: Int, callBack: UICallBack) {
        MyDialog.showAlertDialog(context, "运单重复($result)，是否撤销？", "是", "否",
                { dialog, _ ->
                    dialog.dismiss()
                    deleteWaybill(context, result, loadInfo, unloadEntity, operType, planTaskList, loadType, callBack)
                },
                { dialog, _ ->
                    dialog.dismiss()
                })
    }

    /**
     * 装卸车运单撤销
     * @param operType 11-装车撤销，22-快递卸车撤销
     */
    private fun deleteWaybill(context: Context, result: String, loadInfo: LoadInfo?,
                              unloadEntity: QueryUnLoadDetailBillcode?, operType: Int, planTaskList: MutableList<CarPlanTaskEntity>,
                              loadType: Int, callBack: UICallBack) {
        if (UcWaybillValidate.validate(result)) {
            //撤销优速快递的运单
            val deptType = SharedPreferUtil.getInstance().getIntValue(Common.DEPT_TYPE)
            if (loadInfo != null) {
                //装车撤销
                var hasFlag = false
                val records = mutableListOf<CancleScanLoad>()
                val cancleScanLoadRequest = CancleScanLoadRequest()
//                if (result == loadInfo.waybillNo) {
//                    //主单撤销
//                    for (item in loadInfo.childList) {
//                        val cancleScanLoad = CancleScanLoad(loadInfo.waybillNo, item.childWaybillNo, loadInfo.packageNo, loadInfo.stowageNo, operType, 2,
//                                deptType, 2, loadInfo.stowageNo, SharedPreferUtil.getInstance().getValue(Common.USER_CODE),
//                                SharedPreferUtil.getInstance().empName, SharedPreferUtil.getInstance().deptCode)
//                        records.add(cancleScanLoad)
//                    }
//                    cancleScanLoadRequest.records = records
//                    cancelMasterBillcode(context, cancleScanLoadRequest, loadInfo, null, planTaskList, loadType, callBack)
//                } else {
                //子单撤销
                if (loadInfo.childList != null) {
                    for (item in loadInfo.childList) {
                        if (result == item.childWaybillNo) {
                            if (item.flag == 1) {
                                hasFlag = true
                                val cancleScanLoad = CancleScanLoad(loadInfo.waybillNo, item.childWaybillNo, loadInfo.packageNo, item.stowageNo, operType, 2,
                                        deptType, 2, loadInfo.carMark, SharedPreferUtil.getInstance().getValue(Common.USER_CODE),
                                        SharedPreferUtil.getInstance().empName, SharedPreferUtil.getInstance().deptCode)
                                records.add(cancleScanLoad)
                            }
                        }
                    }
                }
                if (hasFlag) {
                    cancleScanLoadRequest.records = records
                    cancelMasterBillcode(context, cancleScanLoadRequest, loadInfo, null, planTaskList, loadType, callBack)
                } else {
                    SoundVibratorManager.playSound(2)
                    ToastUtil.showToast("主单号中没有扫描的子单号！")
                }
                return
//                }
            } else {
                //卸车撤销
                var hasFlag = false
                val records = mutableListOf<CancleScanLoad>()
                val cancleScanLoadRequest = CancleScanLoadRequest()
//                if (result == unloadEntity?.waybillNo) {
//                    unloadEntity.childList.forEach { child ->
//                        val cancleScanLoad = CancleScanLoad(unloadEntity.waybillNo, child.childWaybillNo, unloadEntity.packageNo,
//                                unloadEntity.stowageNo, operType, 2, deptType, 2, unloadEntity.stowageNo,
//                                SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().empName,
//                                SharedPreferUtil.getInstance().deptCode)
//                        records.add(cancleScanLoad)
//                    }
//                    cancleScanLoadRequest.records = records
//                    cancelMasterBillcode(context, cancleScanLoadRequest, null, unloadEntity, planTaskList, loadType, callBack)
//                } else {
                unloadEntity?.childList?.let {
                    unloadEntity.childList.forEach { child ->
                        if (result == child.childWaybillNo) {
                            if (child.flag == 1) {
                                hasFlag = true
                                val cancleScanLoad = CancleScanLoad(unloadEntity.waybillNo, child.childWaybillNo, unloadEntity.packageNo,
                                        child.stowageNo, operType, 2, deptType, 2, unloadEntity.taskNo,
                                        SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().empName,
                                        SharedPreferUtil.getInstance().deptCode)
                                records.add(cancleScanLoad)
                            }
                        }
                    }
                }
                if (hasFlag) {
                    cancleScanLoadRequest.records = records
                    cancelMasterBillcode(context, cancleScanLoadRequest, null, unloadEntity, planTaskList, loadType, callBack)
                } else {
                    SoundVibratorManager.playSound(2)
                    ToastUtil.showToast("主单号中没有扫描的子单号！")
                }
                return
//                }
            }
        } else {
            //撤销子单号
            if (loadInfo?.childList != null && loadInfo.childList.size > 0) {
                for (item in loadInfo.childList) {
                    //查询单号是否扫描
                    if (item.childWaybillNo == result) {
                        if (item.flag == 1) {
                            /**撤销已扫描的运单 */
                            cancelBillcode(context, result, operType, loadInfo, item, planTaskList, loadType, callBack)
                        } else {
                            SoundVibratorManager.playSound(2)
                            ToastUtil.showToast("运单号未扫描！($result)")
                        }
                        return
                    }
                }
            }
        }
    }

    /**
     * 撤销已扫描的主单号
     */
    private fun cancelMasterBillcode(context: Context, cancleScanLoadRequest: CancleScanLoadRequest, loadInfo: LoadInfo?,
                                     unloadEntity: QueryUnLoadDetailBillcode?, planTaskList: MutableList<CarPlanTaskEntity>,
                                     loadType: Int, callBack: UICallBack) {
        LoadUtils.showLoading("正在撤销扫描数据...", context)
        NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse::class.java)
                .setUrl(Constants.URL_CANCLE_LOAD)
                .setRequestObject(cancleScanLoadRequest)
                .execute(object : UICallBack() {
                    override fun onError(msg: String) {
                        LoadUtils.hideLoading(context)
                        if (msg == Constants.PLEASE_CHECK_NET) {
                            //断网撤销本地未上传的数据
                            if (updateWaybillNoStatus(cancleScanLoadRequest, loadInfo, unloadEntity, planTaskList, loadType, msg)) {
                                SoundVibratorManager.playSound(1)
                                callBack.onSuccess(msg)
                            }
                        } else {
                            SoundVibratorManager.playSound(2)
                            ToastUtil.showToast(msg)
                            callBack.onError(msg)
                        }
                    }

                    override fun onSuccess(obj: Any) {
                        if (obj is NoDataResponse) {
                            LoadUtils.hideLoading(context)

                            if (updateWaybillNoStatus(cancleScanLoadRequest, loadInfo, unloadEntity, planTaskList, loadType, null)) {
                                SoundVibratorManager.playSound(1)
                                callBack.onSuccess(obj)
                            }
                        }
                    }
                })
    }

    /**
     * 修改运单状态
     * @param loadType 1-装车，2-卸车
     */
    private fun updateWaybillNoStatus(cancleScanLoadRequest: CancleScanLoadRequest, loadInfo: LoadInfo?,
                                      unloadEntity: QueryUnLoadDetailBillcode?, planTaskList: MutableList<CarPlanTaskEntity>,
                                      loadType: Int, msg: String?): Boolean {
        val mUnloadScanTableDao = UnloadScanTableDao()
        //设置未扫描
        if (loadInfo != null) {
            loadInfo.childList?.forEach { child ->
                cancleScanLoadRequest.records.forEach { cancle ->
                    if (cancle.childWaybillNo == child.childWaybillNo) {
                        if (msg != null && msg == Constants.PLEASE_CHECK_NET) {
                            //查询未上传的运单设置为未扫描状态
                            val scanTable = mUnloadScanTableDao.getScanWayBillData(loadInfo.stowageNo, loadType, cancle.childWaybillNo)
                            if (scanTable?.isUpload != 1) {
                                if (child.flag == 1) {
                                    child.flag = 0
                                }
                            } else {
                                ToastUtil.showToast("撤销失败：运单已上传")
                                return false
                            }
                        } else {
                            if (child.flag == 1) {
                                child.flag = 0
                            }
                        }
                    }
                }
            }
        } else {
            unloadEntity?.childList?.forEach { child ->
                cancleScanLoadRequest.records.forEach { cancle ->
                    if (cancle.childWaybillNo == child.childWaybillNo) {
                        if (msg != null && msg == Constants.PLEASE_CHECK_NET) {
                            //查询未上传的运单设置为未扫描状态
                            val scanTable = mUnloadScanTableDao.getScanWayBillData(unloadEntity.stowageNo, loadType, cancle.childWaybillNo)
                            if (scanTable?.isUpload != 1) {
                                if (child.flag == 1) {
                                    child.flag = 0
                                }
                            } else {
                                ToastUtil.showToast("撤销失败：运单已上传")
                                SoundVibratorManager.playSound(2)
                                return false
                            }
                        } else {
                            if (child.flag == 1) {
                                child.flag = 0
                            }
                        }
                    }
                }
            }
        }
        //删除数据库
        try {
            val cancleScanLoads = cancleScanLoadRequest.records
            for (cancleScanLoad in cancleScanLoads) {
                for (planTask in planTaskList) {
                    planTask.loadTasks?.forEach { loadTask ->
                        val result = mUnloadScanTableDao.deleteByChildWaybill(loadTask.stowageNo, cancleScanLoad.childWaybillNo, loadType)
                        if (result < 0) {
                            ToastUtil.showToast("数据库删除失败！")
                            SoundVibratorManager.playSound(2)
                            return false
                        }
                    }
                }
                //发送消息清除手动添加列表
                EventBus.getDefault().post(ScanResult(cancleScanLoad.childWaybillNo, 9, 9))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    }

    /**
     * 撤销已扫描的子单号
     */
    private fun cancelBillcode(context: Context, result: String, operType: Int, billDto: LoadInfo,
                               item: QueryLoadDetailChildBillcode, planTaskList: MutableList<CarPlanTaskEntity>,
                               loadType: Int, callBack: UICallBack) {
        try {
            val deptType = SharedPreferUtil.getInstance().getIntValue(Common.DEPT_TYPE)
            val mCancleScanLoadRequest = CancleScanLoadRequest()
            val records: MutableList<CancleScanLoad> = ArrayList()
            val mCancleScanLoad = CancleScanLoad(billDto.waybillNo, result, billDto.packageNo,
                    if (item.stowageNo == null) billDto.stowageNo else item.stowageNo, operType,
                    2, deptType, if (UcWaybillValidate.validate(billDto.waybillNo)) 2 else 1,
                    billDto.stowageNo, SharedPreferUtil.getInstance().getValue(Common.USER_CODE),
                    SharedPreferUtil.getInstance().empName, SharedPreferUtil.getInstance().deptCode)
            records.add(mCancleScanLoad)
            mCancleScanLoadRequest.records = records
            LoadUtils.showLoading("正在撤销扫描数据...", context)
            NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setResponsClazz(NoDataResponse::class.java)
                    .setUrl(Constants.URL_CANCLE_LOAD)
                    .setRequestObject(mCancleScanLoadRequest)
                    .execute(object : UICallBack() {
                        override fun onError(msg: String) { //开启扫描
                            LoadUtils.hideLoading(context)
                            if (msg == Constants.PLEASE_CHECK_NET) {
                                if (updateChildWaybillStatus(result, billDto, item, planTaskList, loadType, msg)) {
                                    SoundVibratorManager.playSound(1)
                                    callBack.onSuccess(msg)
                                }
                            } else {
                                SoundVibratorManager.playSound(2)
                                ToastUtil.showToast(msg)
                                callBack.onError(msg)
                            }
                        }

                        override fun onSuccess(obj: Any) {
                            if (obj is NoDataResponse) {
                                if (updateChildWaybillStatus(result, billDto, item, planTaskList, loadType, null)) {
                                    LoadUtils.hideLoading(context)
                                    SoundVibratorManager.playSound(1)
                                    callBack.onSuccess(obj)
                                }
                            }
                        }
                    })
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 更新子单状态
     */
    private fun updateChildWaybillStatus(result: String, billDto: LoadInfo, item: QueryLoadDetailChildBillcode,
                                         planTaskList: MutableList<CarPlanTaskEntity>,
                                         loadType: Int, msg: String?): Boolean {
        if (msg != null && msg == Constants.PLEASE_CHECK_NET) {
            //查询未上传的运单设置为未扫描状态
            val scanTable = UnloadScanTableDao().getScanWayBillData(billDto.stowageNo, loadType, result)
            if (scanTable?.isUpload != 1) {
                item.flag = 0
            } else {
                ToastUtil.showToast("撤销失败：运单已上传")
                SoundVibratorManager.playSound(2)
                return false
            }
        } else {
            item.flag = 0
        }

        //删除数据库
        try {
            val mUnloadScanTableDao = UnloadScanTableDao()
            for (planTask in planTaskList) {
                planTask.loadTasks?.forEach { loadTask ->
                    val result = mUnloadScanTableDao.deleteByChildWaybill(loadTask.stowageNo, result, loadType)
                    if (result < 0) {
                        ToastUtil.showToast("数据库删除失败！")
                    }
                }
            }
            if (billDto.type == 1 && billDto.goodsPriority != null && billDto.goodsPriority.toInt() == Common.GOODSP_RIORITY_CHUAN) {
                //删除最后一条串货运单
                LoadScanActivity.loadInfos.remove(billDto)
            }
        } catch (e: SQLException) {
            e.printStackTrace()
        }
        return true
    }

    /**
     * 发送消息给首页处理待办事项数据，将完成的数据清除
     * @param fromActivity 1-装车扫描界面，2-卸车扫描界面，3-装车封车完成，4-卸车完成
     */
    @JvmStatic
    fun sendEventToSouYe(fromActivity: Int, taskNo: String?, planTaskList: MutableList<CarPlanTaskEntity>?) {
        val event = CreateStowagesEvent()
        event.fromActivity = fromActivity

        val taskNos = mutableListOf<String>()
        if (fromActivity == 3) {
            if (taskNo != null) {
                taskNos.add(taskNo)
            }
        } else {
            if (planTaskList != null) {
                for (planTask in planTaskList) {
                    taskNos.add(planTask.taskNo)
                }
            }
        }

        event.taskNos = taskNos
        EventBus.getDefault().post(event)
    }

    /**
     * 默认选择 快运 或 者快 递类型
     */
    @JvmStatic
    fun createCheckTaskType(planTaskList: MutableList<CarPlanTaskEntity>?, cbYm: CheckBox, cbUC: CheckBox) {
        if (planTaskList != null) {
            var hasBeTask = false
            planTaskList.forEach { planTask ->
                if (planTask.beTask == 1) {
                    hasBeTask = true
                }
            }

            if (hasBeTask) {
                //车线任务
                var hasLoadTask = false
                cbYm.isChecked = false
                cbUC.isChecked = false
                planTaskList.forEach { planTask ->
                    planTask.loadTasks?.forEach { loadTask ->
                        hasLoadTask = true
                        if (loadTask.stowageNo.startsWith("P")) {
                            cbYm.isChecked = true
                        } else {
                            cbUC.isChecked = true
                        }
                    }
                }

                if (!hasLoadTask) {
                    //查询网点类型
                    val departmentTable = DepartmentTableDao().queryDeptByDeptCode(SharedPreferUtil.getInstance().deptCode)
                    if (departmentTable != null) {
                        when (departmentTable.isOmg) {
                            0 -> {
                                cbYm.isChecked = true
                                cbUC.isChecked = false
                            }
                            1 -> {
                                cbYm.isChecked = false
                                cbUC.isChecked = true
                            }
                            else -> {
                                cbYm.isChecked = true
                                cbUC.isChecked = true
                            }
                        }
                    }
                }
            } else {
                cbYm.isEnabled = false
                cbUC.isEnabled = false
                for (planTask in planTaskList) {
                    if (planTask.loadTasks != null) {
                        for (loadTask in planTask.loadTasks) {
                            if (loadTask.stowageNo.startsWith("P")) {
                                cbYm.isChecked = true
                            } else {
                                cbUC.isChecked = true
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 校验选择配载任务
     *
     * @return boolean
     */
    @JvmStatic
    fun checkSelectStowageTask(loadTaskList: List<LoadBillTaskEntity>?, carPlaneTasks: List<CarPlanTaskEntity>?): Boolean {

        if (!checkSelectStowageTaskForUnload(loadTaskList, carPlaneTasks)) {
            return false
        }

        //限制选择相同下一站
//        for (i in loadTaskList!!.indices) {
//            val preTask: LoadBillTaskEntity = loadTaskList[i]
//            if (preTask.isCheck) {
//                for (j in i + 1 until loadTaskList.size) {
//                    val nextTask: LoadBillTaskEntity = loadTaskList[j]
//                    if (preTask.destDeptCode == nextTask.destDeptCode) {
//                        ToastUtil.showToast("不能选择相同下一站任务！")
//                        SoundVibratorManager.playSound(2)
//                        return false
//                    }
//                }
//            }
//        }
        if (ListUtils.judgeIsContainsNextStation(loadTaskList)) {
            ToastUtil.showToast("不能选择相同下一站任务！")
            SoundVibratorManager.playSound(2)
            return false
        }

        return true
    }

    /**
     * 校验选择配载任务
     *
     * @return boolean
     */
    @JvmStatic
    fun checkSelectStowageTaskForUnload(loadTaskList: List<LoadBillTaskEntity>?, carPlaneTasks: List<CarPlanTaskEntity>?): Boolean {
        if (loadTaskList == null || loadTaskList.isEmpty()) {
            ToastUtil.showToast("无配载任务！")
            SoundVibratorManager.playSound(2)
            return false
        }

        var selectNext = false
        for (loadTask in loadTaskList) {
            if (loadTask.isCheck) {
                selectNext = true
            }
        }
        if (!selectNext) {
            ToastUtil.showToast("请选择至少一个配载单卸车")
            SoundVibratorManager.playSound(2)
            return false
        }

        return true
    }

    /**
     * 融合 合并装车提示
     */
    @JvmStatic
    fun showMergeLoadDialog(context: Context, onClickListener: DialogInterface.OnClickListener) {
        MyDialog.showAlertDialog(context, "是否确认合并装车？\n存在错分风险！", "是", "否",
                DialogInterface.OnClickListener { dialog, which ->
                    dialog.dismiss()
                    onClickListener.onClick(dialog, which)
                }, DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() })
    }

    /**
     * 更新运单上传失败状态
     *
     * @param list
     */
    @JvmStatic
    fun updateErrorWaybillStatus(list: List<UnloadScanTable>, unloadScanTableDao: UnloadScanTableDao) {
        try {
            for (scanTable in list) {
                scanTable.isUpload = 2
                unloadScanTableDao.update(scanTable)
            }
        } catch (e: SQLException) {
            e.printStackTrace()
        }
    }

    /**
     * 设置为上传件数
     */
    @JvmStatic
    fun setUnloadCount(num: TextView, carPlanTaskEntityList: List<CarPlanTaskEntity>?,
                       mUnloadScanTableDao: UnloadScanTableDao, operTypeCode: Int) {
        Observable.create<Long> { subscriber ->
            var unloadCount: Long = 0
            if (carPlanTaskEntityList != null) {
                for (entity in carPlanTaskEntityList) { //查询未上传数据
                    if (entity.loadTasks != null) {
                        for (loadTask in entity.loadTasks) {
                            unloadCount += mUnloadScanTableDao.getUnUploadData(loadTask.stowageNo, operTypeCode)
                        }
                    }
                }
            }
            subscriber.onNext(unloadCount)
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Subscriber<Long?>() {
            override fun onCompleted() {}
            override fun onError(throwable: Throwable) {}
            override fun onNext(unloadCount: Long?) {
                num.text = String.format("%s", unloadCount)
            }
        })
    }

    /**
     * 获取上传失败的运单
     */
    @JvmStatic
    fun getErrorList(carPlanTaskEntityList: List<CarPlanTaskEntity>?, mUnloadScanTableDao: UnloadScanTableDao,
                     operTypeCode: Int): List<UnloadScanTable>? {
        val errorList = mutableListOf<UnloadScanTable>()
        if (carPlanTaskEntityList != null) {
            for (entity in carPlanTaskEntityList) {
                //查询未上传数据
                if (entity.loadTasks != null) {
                    for (loadTask in entity.loadTasks) {
                        val unloadScanTables = mUnloadScanTableDao.getErrorData(2, loadTask.stowageNo, operTypeCode)
                        if (unloadScanTables != null) {
                            errorList.addAll(unloadScanTables)
                        }
                    }
                }
            }
        }
        return errorList
    }

    /**
     * 查询线路上下一站
     * @param operType 1-装车，2-卸车
     * @param station 上下一站(可模糊匹配)
     */
    @JvmStatic
    fun querySourceArriveByStation(operType: Int, station: String, callBack: UICallBack) {
        val params: MutableMap<String, String> = HashMap(2)
        params["operationType"] = operType.toString()
        params["thisStationCode"] = SharedPreferUtil.getInstance().deptCode
        params["station"] = station

        NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_SOURCE_ARRIVE_STATION)
                .setResponsClazz(QuerySourceArriveStationResponse::class.java)
                .setParams(params)
                .execute(object : UICallBack() {
                    override fun onSuccess(obj: Any?) {
                        val response = obj as QuerySourceArriveStationResponse
                        if (!response.data.isNullOrEmpty()) {
                            val lineList = if (operType == 1) {
                                //装车，选择下一站
                                Common.getDestLineList(response.data)
                            } else {
                                //卸车，选择上一站
                                Common.getSourceLineList(response.data)
                            }
                            callBack.onSuccess(lineList)
                        } else {
                            if (operType == 1) {
                                callBack.onError("未查询到下一站！")
                            } else {
                                callBack.onError("未查询到上一站！")
                            }
                        }
                    }

                    override fun onError(msg: String?) {
                        callBack.onError(msg)
                    }
                })
    }

}